package com.conncui.io.file;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

/**
 * Created by cui on 15-12-23.
 */
public class FileRW {

    ExecutorService executorService;
    private File mFile;
    private FileWriter mFileWriter;

    public FileRW() {

    }

    public FileRW(File file) {
        this.mFile = file;
        if (!mFile.exists()) {
            try {
                mFile.createNewFile();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        executorService = Executors.newCachedThreadPool();
    }

    public void write(final String string) {
        executorService.execute(new Runnable() {
            @Override
            public void run() {
                try {
                    mFileWriter = new FileWriter(mFile, true);
                    mFileWriter.write(string);
                    mFileWriter.flush();
                    System.out.println("save");

                } catch (IOException e) {
                    System.out.println("save IOException");

                    e.printStackTrace();
                } finally {
                    if (mFileWriter != null) {
                        try {
                            mFileWriter.close();
                        } catch (IOException e) {
                            e.printStackTrace();
                        }
                    }
                }
            }
        });

    }

    public String read() {
        BufferedReader reader = null;
        StringBuilder stringBuilder = new StringBuilder();
        String line;
        try {
            reader = new BufferedReader(new FileReader(mFile));
            while (null != (line = reader.readLine())) {
                stringBuilder.append(line);
            }
        } catch (FileNotFoundException e) {
            e.printStackTrace();
            System.out.println(e.toString());

        } catch (IOException e) {
            e.printStackTrace();
            System.out.println(e.toString());
        } finally {
            if (reader != null) {
                try {
                    reader.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
        return stringBuilder.toString();
    }

    public FileWriter getmFileWriter() {
        return mFileWriter;
    }

    public File getFile() {
        return mFile;
    }
}
